<template>
  <div class="userManagement">
    <div class="searchBox">
      <div class="itemBox">
        <div class="itemTitle">用户信息</div>
        <el-input
          class="itemInput"
          v-model="userInfo"
          placeholder="请输入用户姓名/账号/手机号码"
        />
      </div>
      <div class="itemBox">
        <div class="itemTitle">角色</div>
        <el-select v-model="roleId" placeholder="请选择" class="itemInput">
          <el-option
            v-for="item in roleOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="itemBox">
        <div class="itemTitle">状态</div>
        <el-select v-model="state" placeholder="请选择" class="itemInput">
          <el-option
            v-for="item in stateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="itemBox">
        <div class="itemTitle">创建人</div>
        <el-input
          class="itemInput"
          v-model="creatorName"
          placeholder="请输入创建人姓名"
        />
      </div>
      <div class="itemBox">
        <div class="itemTitle">创建时间</div>
        <el-date-picker
          v-model="creationTime"
          class="creationTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
        />
        <img src="@/assets/images/changeTime.png" alt="" class="timeImg" />
      </div>
      <!--   操作按钮   -->
      <div class="operationBox">
        <div class="resetBox" @click="reset()">重置</div>
        <div class="queryBox" @click="getDatalist()">查询</div>
      </div>
    </div>
    <div class="content">
      <div class="addBox" @click="addUser()">新增</div>
      <div class="tableBox">
        <el-table
          :data="tableData"
          style="width: 100%"
          height="600"
          :header-cell-style="{
            background: '#F7F8FA',
            color: '#203549',
          }"
        >
          <el-table-column type="index" label="序号" align="center">
            <template slot-scope="scope">
              {{
                (pageData.currentPage - 1) * pageData.pageSize +
                scope.$index +
                1
              }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="用户名" align="center" />
          <el-table-column
            prop="accountNumber"
            label="用户账号"
            align="center"
          />
          <el-table-column prop="phone" label="手机号" align="center" />
          <el-table-column label="性别" align="center">
            <template slot-scope="scope">
              {{ scope.row.gender == 2 ? '女' : '男' }}
            </template>
          </el-table-column>
          <el-table-column prop="roleName" label="角色" align="center" />
          <el-table-column label="状态" align="center">
            <template slot-scope="scope" v-if="scope.row.isRoot == 0">
              <el-switch
                v-model="scope.row.isDisabled"
                active-color="#0CD13A"
                inactive-color="#D3D3D6"
                @change="changeState(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="creatorName" label="创建人" align="center" />
          <el-table-column label="创建时间" align="center">
            <template slot-scope="scope">
              {{
                scope.row.createTime ? scope.row.createTime.slice(0, 10) : ''
              }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <div class="tableOperation" v-if="scope.row.isRoot == 0">
                <div @click="handleEdit(scope.row)" class="edit">编辑</div>
                <div @click="handleDelete(scope.row)" class="delete">删除</div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <Pagination @getData="getData" :pageData="pageData" />
    </div>

    <!--  新增/编辑用户  -->
    <el-dialog :visible.sync="dialogVisible" width="600px" class="addDialog">
      <div class="dialogContent">
        <div class="header">{{ dialogType == 0 ? '新增' : '编辑' }}用户</div>
        <div class="main">
          <div class="baseMsg">
            <div class="title"><span>*</span>基础信息</div>
            <div class="formBox">
              <el-form
                :model="ruleForm"
                hide-required-asterisk
                :rules="dialogType == 0 ? rules : rulesEdit"
                ref="ruleForm"
                label-width="73px"
                class="demo-ruleForm"
              >
                <el-form-item label="用户账号" prop="userNumber">
                  <el-input v-model="ruleForm.userNumber" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input v-model="ruleForm.password" />
                </el-form-item>
                <el-form-item label="确认密码" prop="surePassword">
                  <el-input v-model="ruleForm.surePassword" />
                </el-form-item>
                <el-form-item label="用户姓名" prop="userName">
                  <el-input v-model="ruleForm.userName" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                  <el-select v-model="ruleForm.gender" placeholder="请选择性别">
                    <el-option label="男" value="1" />
                    <el-option label="女" value="2" />
                  </el-select>
                </el-form-item>
                <el-form-item label="手机号码" prop="phoneNumber">
                  <el-input v-model="ruleForm.phoneNumber" />
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div class="roleManagement">
            <div class="title">角色管理</div>
            <div class="changeRoleBox">
              <el-checkbox-group
                v-model="checkedCities"
                @change="handleCheckedCitiesChange"
              >
                <el-checkbox v-for="city in cities" :label="city" :key="city">{{
                  city
                }}</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </div>
        <div class="hr"></div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination';
import debounce from '@/utils/js/debounce';
import { timeMode } from '@/utils/js/util';
export default {
  name: 'UserManagement',
  data() {
    return {
      // 新增用户弹窗
      dialogVisible: false,

      // 0--新增用户  1--编辑用户
      dialogType: 0,

      // 用户信息
      userInfo: '',

      // 角色
      roleId: '0',
      roleOptions: [
        {
          value: '0',
          label: '全部',
        },
      ],

      // 状态
      state: '0',
      stateOptions: [
        {
          value: '0',
          label: '全部',
        },
        {
          value: '1',
          label: '开启',
        },
        {
          value: '2',
          label: '禁用',
        },
      ],

      // 创建人
      creatorName: '',

      //  创建时间
      creationTime: '',

      tableData: [],

      // 传给分页的数据
      pageData: {
        total: 400,
        pageSize: 10,
        currentPage: 1,
      },

      ruleForm: {
        userNumber: '',
        gender: '',
        password: '',
        surePassword: '',
        userName: '',
        phoneNumber: '',
      },
      rules: {
        userNumber: [
          { validator: this.getValidatorUserNumber(), trigger: 'blur' },
          {
            min: 1,
            max: 20,
            message: '用户账号长度为1-20位',
            trigger: 'blur',
          },
        ],
        gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
        password: [
          { validator: this.getValidatorPassword(), trigger: 'blur' },
          {
            min: 8,
            max: 20,
            message:
              '请输入8至20位大小写英文字母、特殊符号、数字其中任意三种的组合',
            trigger: 'blur',
          },
        ],
        surePassword: [
          { validator: this.getValidatorSurePassword(), trigger: 'blur' },
          {
            min: 8,
            max: 20,
            message:
              '请输入8至20位大小写英文字母、特殊符号、数字其中任意三种的组合',
            trigger: 'blur',
          },
        ],
        userName: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' },
        ],
        phoneNumber: [
          { validator: this.getValidatorPhoneNumber(), trigger: 'blur' },
        ],
      },
      rulesEdit: {
        userNumber: [
          { validator: this.getValidatorUserNumber(), trigger: 'blur' },
        ],
        gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
        password: [
          { validator: this.getValidatorPasswordEdit(), trigger: 'blur' },
          {
            min: 8,
            max: 20,
            message:
              '请输入8至20位大小写英文字母、特殊符号、数字其中任意三种的组合',
            trigger: 'blur',
          },
        ],
        surePassword: [
          { validator: this.getValidatorSurePasswordEdit(), trigger: 'blur' },
          {
            min: 8,
            max: 20,
            message:
              '请输入8至20位大小写英文字母、特殊符号、数字其中任意三种的组合',
            trigger: 'blur',
          },
        ],
        userName: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' },
        ],
        phoneNumber: [
          { validator: this.getValidatorPhoneNumber(), trigger: 'blur' },
        ],
      },

      checkedCities: [],
      cities: [],

      // 当前登录的用户id
      accountId: sessionStorage.getItem('accountId'),

      //  修改信息时需要的用户id
      userId: '',
    };
  },
  mounted() {
    this.getDatalist();
    this.getRoleList();
  },
  methods: {
    // 获取当前医院的所有角色
    getRoleList() {
      this.$http
        .getRolesHospital(Number(this.accountId))
        .then(res => {
          let { data } = res;
          let arr = [
              {
                value: '0',
                label: '全部',
              },
            ],
            roleArr = [];

          data.forEach(item => {
            arr.push({
              value: item.roleId,
              label: item.roleName,
            });
            roleArr.push(item.roleName);
          });

          this.roleOptions = arr;
          this.cities = roleArr;
        })
        .catch(() => {});
    },

    // 获取列表数据
    getDatalist() {
      let startTime = '',
        endTime = '';
      if (this.creationTime) {
        startTime = timeMode(this.creationTime[0]).datestr;
        endTime = timeMode(this.creationTime[1]).datestr;
      }
      let params = {
        pageSize: this.pageData.pageSize,
        currentPage: this.pageData.currentPage,
        accountId: Number(this.accountId),
        userInfo: this.userInfo,
        roleId: this.roleId == 0 ? '' : this.roleId,
        isDisabled: this.state == 0 ? '' : this.state - 1,
        creatorName: this.creatorName,
        startTime,
        endTime,
      };
      this.$http
        .showAccountHospital(params)
        .then(res => {
          let { data } = res;
          if (data && Array.isArray(data.records)) {
            data.records.forEach(item => {
              item.isDisabled = item.isDisabled == 0 ? true : false;
            });
            this.tableData = data.records;

            this.pageData = {
              total: data.total,
              pageSize: this.pageData.pageSize,
              currentPage: this.pageData.currentPage,
            };
          }
        })
        .catch(() => {});
    },

    //  重置
    reset() {
      this.userInfo = '';
      this.roleId = '0';
      this.state = '全部';
      this.creatorName = '';
      this.creationTime = '';
      this.pageData = {
        total: 10,
        pageSize: 10,
        currentPage: 1,
      };
      this.getDatalist();
    },

    // 新增
    addUser() {
      this.dialogType = 0;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs['ruleForm'].resetFields();
        this.ruleForm = {
          userNumber: '',
          gender: '',
          password: '',
          surePassword: '',
          userName: '',
          phoneNumber: '',
        };
      });
    },

    // 用户新增角色选择
    handleCheckedCitiesChange(value) {
      this.checkedCities = [value[value.length - 1]];
    },

    // 用户新增/编辑确定
    submitForm: debounce(function (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (!this.checkedCities.length) {
            this.$message.error('请选择角色！');
          } else {
            let roleId = '';
            this.roleOptions.forEach(item => {
              if (item.label == this.checkedCities.join(','))
                roleId = item.value;
            });
            let params = {
              accountNumber: this.ruleForm.userNumber,
              accountId: this.accountId,
              password: this.ruleForm.password,
              name: this.ruleForm.userName,
              gender: this.ruleForm.gender,
              phone: this.ruleForm.phoneNumber,
              roleId,
            };
            if (this.dialogType == 0) {
              this.$http
                .addAccountHospital(params)
                .then(res => {
                  let { code } = res;
                  if (code == '0000000000') {
                    this.$message({
                      type: 'success',
                      message: '新增成功!',
                    });
                    this.dialogVisible = false;
                    this.$refs['ruleForm'].resetFields();
                    this.getDatalist();
                  } else {
                    this.$message({
                      showClose: true,
                      message: res.msg,
                      type: 'error',
                    });
                  }
                })
                .catch(() => {});
            } else {
              if (params.gender == '男' || params.gender == '女')
                params.gender = params.gender == '男' ? 1 : 2;
              params.accountId = this.userId;
              this.$http
                .editAccountHospital(params)
                .then(res => {
                  let { code } = res;
                  if (code == '0000000000') {
                    this.$message({
                      type: 'success',
                      message: '修改成功!',
                    });
                    this.dialogVisible = false;
                    this.getDatalist();
                  } else {
                    this.$message({
                      showClose: true,
                      message: res.msg,
                      type: 'error',
                    });
                  }
                })
                .catch(() => {});
            }
          }
        } else {
          return false;
        }
      });
    }),

    // 用户新增取消
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.checkedCities = [];
      this.dialogVisible = false;
    },

    // 状态是否禁用
    changeState(val) {
      if (val.accountId == this.accountId) {
        this.$message({
          showClose: true,
          message: '当前账号属于正在登录账号，不可禁用！',
          type: 'error',
        });
        val.isDisabled = true;
      } else {
        if (!val.isDisabled) {
          this.$confirm('此操作将禁用该账号, 是否继续?', '禁用', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              this.$http
                .banAccountHospital(val.accountId)
                .then(res => {
                  if (res.code == '0000000000') {
                    this.$message({
                      type: 'success',
                      message: '禁用成功!',
                    });
                  }
                })
                .catch(() => {});
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消禁用',
              });
              val.isDisabled = true;
            });
        } else {
          this.$http
            .banAccountHospital(val.accountId)
            .then(res => {
              if (res.code == '0000000000') {
                this.$message({
                  type: 'success',
                  message: '开启成功!',
                });
              }
            })
            .catch(() => {});
        }
      }
    },

    //  分页数据改变
    getData(val) {
      this.pageData = val;
      this.getDatalist();
    },

    // 编辑
    handleEdit(val) {
      this.dialogType = 1;
      this.ruleForm.userNumber = val.accountNumber;
      this.ruleForm.userName = val.name;
      this.ruleForm.phoneNumber = val.phone;
      this.ruleForm.gender = val.gender == 1 ? '男' : '女';
      this.checkedCities = [val.roleName];
      this.dialogVisible = true;
      this.userId = val.accountId;
    },

    //  删除
    handleDelete(val) {
      if (val.accountId == this.accountId) {
        this.$message({
          showClose: true,
          message: '当前账号属于正在登录账号，不可删除！',
          type: 'error',
        });
      } else {
        this.$confirm('此操作将删除该账号, 是否继续?', '删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.$http.delAccountHospital(val.accountId).then(res => {
              if (res.code == '0000000000') {
                this.$message({
                  type: 'success',
                  message: '删除成功!',
                });
                this.getDatalist();
              }
            });
          })
          .catch(() => {});
      }
    },

    // 校验用户账号
    getValidatorUserNumber() {
      return (rule, value, callback) => {
        if (this.ruleForm.userNumber === '') {
          callback(new Error('用户账号不能为空!'));
        } else {
          let srt = /^[A-Za-z]+$/;
          if (!srt.test(this.ruleForm.userNumber)) {
            callback(new Error('用户账号只允许输入大小写英文字母!'));
          }
          callback();
        }
      };
    },

    // 校验密码
    getValidatorPassword() {
      return (rule, value, callback) => {
        if (this.ruleForm.password === '') {
          callback(new Error('密码不能为空!'));
        } else {
          let srt =
            /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{8,20}$/;
          if (!srt.test(this.ruleForm.password)) {
            callback(
              new Error(
                '请输入8至20位大小写英文字母、特殊符号、数字其中任意三种的组合!'
              )
            );
          }
          callback();
        }
      };
    },

    // 校验确认密码
    getValidatorSurePassword() {
      return (rule, value, callback) => {
        if (this.ruleForm.surePassword === '') {
          callback(new Error('确认密码不能为空!'));
        } else if (this.ruleForm.password === '') {
          callback(new Error('请先输入密码！'));
        } else if (this.ruleForm.surePassword !== this.ruleForm.password) {
          callback(new Error('两次密码不一致!'));
        } else {
          callback();
        }
      };
    },

    // 验证手机号码
    getValidatorPhoneNumber() {
      return (rule, value, callback) => {
        if (this.ruleForm.phoneNumber === '') {
          callback(new Error('手机号码不能为空!'));
        } else {
          let srt = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
          if (!srt.test(this.ruleForm.phoneNumber)) {
            callback(new Error('手机号码不正确！'));
          }
          callback();
        }
      };
    },

    // 校验编辑时的密码
    // 校验密码
    getValidatorPasswordEdit() {
      return (rule, value, callback) => {
        if (this.ruleForm.password) {
          let srt =
            /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{8,20}$/;
          if (!srt.test(this.ruleForm.password)) {
            callback(
              new Error(
                '请输入8至20位大小写英文字母、特殊符号、数字其中任意三种的组合!'
              )
            );
          }
          callback();
        } else {
          callback();
        }
      };
    },

    // 校验确认密码
    getValidatorSurePasswordEdit() {
      return (rule, value, callback) => {
        if (this.ruleForm.password && this.ruleForm.surePassword === '') {
          callback(new Error('确认密码不能为空!'));
        } else if (
          this.ruleForm.surePassword &&
          this.ruleForm.password === ''
        ) {
          callback(new Error('请先输入密码！'));
        } else if (
          this.ruleForm.password &&
          this.ruleForm.surePassword &&
          this.ruleForm.surePassword !== this.ruleForm.password
        ) {
          callback(new Error('两次密码不一致!'));
        } else {
          callback();
        }
      };
    },
  },
  components: {
    Pagination,
  },
};
</script>

<style scoped lang="less">
.userManagement {
  .searchBox {
    height: 112px;
    background: #fff;
    padding: 16px;
    box-sizing: border-box;
    display: flex;
    flex-wrap: wrap;
    .itemBox {
      display: flex;
      align-items: center;
      margin-right: 1%;
      position: relative;
      margin-bottom: 16px;

      .itemTitle {
        font-size: 14px;
        font-weight: 400;
        color: #111111;
        text-align: right;
        white-space: nowrap;
      }
      /deep/ .itemInput {
        margin-left: 8px;

        .el-input__inner {
          width: 240px;
          height: 32px;
        }
        .el-input__icon {
          line-height: 32px;
        }
      }

      /deep/ .creationTime {
        width: 310px;
        height: 32px;
        margin-left: 8px;
        .el-icon-date {
          display: none;
        }
        .el-range-input {
          text-align: left;
        }
        .el-range-separator {
          width: 10%;
          margin-top: -8px;
        }
      }
      .timeImg {
        width: 18px;
        position: absolute;
        right: 8px;
      }
    }
    .operationBox {
      display: flex;
      .resetBox {
        width: 76px;
        height: 32px;
        border-radius: 2px;
        border: 1px solid #dcdfe6;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 14px;
        font-weight: 400;
        color: #606266;
        cursor: pointer;
        box-sizing: border-box;
      }
      .queryBox {
        width: 76px;
        height: 32px;
        background: #0a73e4;
        border-radius: 2px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        font-size: 14px;
        font-weight: 400;
        color: #ffffff;
        margin-left: 8px;
      }
    }
  }
  .content {
    background: #fff;
    padding: 16px;
    box-sizing: border-box;
    margin-top: 16px;
    height: 740px;
    position: relative;
    .addBox {
      width: 76px;
      height: 32px;
      background: #0a73e4;
      border-radius: 2px;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      font-size: 14px;
      font-weight: 400;
      color: #ffffff;
      margin-bottom: 16px;
    }
    .tableBox {
      .tableOperation {
        display: flex;
        .edit {
          font-size: 14px;
          font-weight: 400;
          color: #0a73e4;
          cursor: pointer;
        }
        .delete {
          font-size: 14px;
          font-weight: 400;
          color: #ff595a;
          margin-left: 16px;
          cursor: pointer;
        }
      }
    }
  }
  /deep/ .addDialog {
    .el-dialog__header,
    .el-dialog__body {
      padding: 0;
    }
    .dialogContent {
      .header {
        height: 54px;
        border-bottom: 1px solid #e9e8eb;
        font-size: 16px;
        font-weight: 500;
        color: #101b25;
        line-height: 54px;
        padding-left: 16px;
        box-sizing: border-box;
      }
      .main {
        padding: 24px 98px;
        box-sizing: border-box;
        .baseMsg {
          .title {
            font-size: 14px;
            font-weight: 500;
            color: #101b25;
            span {
              color: #e22424;
            }
          }
        }
        .roleManagement {
          margin-top: 24px;
          .title {
            font-size: 14px;
            font-weight: 500;
            color: #101b25;
          }
          .changeRoleBox {
            margin-top: 16px;
            .el-checkbox {
              margin-right: 28px;
              margin-bottom: 14px;
            }
          }
        }
      }
      .hr {
        height: 2px;
        background: #e9e8eb;
      }
    }
  }
  .formBox {
    margin-top: 16px;
    /deep/ .el-form {
      .el-form-item__label {
        //width: 73px !important;
        line-height: 32px;
        height: 32px;
      }
      .el-form-item__content {
        //margin-left: 73px !important;
        line-height: 32px;
        height: 32px;
      }
      .el-input__inner {
        width: 340px;
        height: 32px;
      }
      .el-form-item {
        margin-bottom: 16px;
      }
    }
  }
}
</style>
